package com.swust.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.swust.security.entity.Users;
import com.swust.security.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author hqf
 * @Date Created in 2021/9/11 9:54
 * @Description
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Resource
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询数据库进行用户密码校验
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Users user = usersMapper.selectOne(wrapper);
        if(user == null){ // 认证失败
            System.out.println("该用户不存在...");
            throw new UsernameNotFoundException("该用户不存在");
        }
        // 添加用户角色和权限
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRole());
        return new User(user.getUsername(),passwordEncoder.encode(user.getPassword()),auths);
    }
}
